<template>
  <!-- 标题区域 -->
  <div v-if="isDialog" class="dialog-title">
    <h2 class="dialog-title-text">账号登录</h2>
  </div>
  <div v-else class="login-title">
    <div class="title-content">
      <img class="logo" src="@/assets/image/logo.png" alt="logo" />
      <h2 class="title-text">
        {{ WEBSITE_NAME }}
      </h2>
    </div>
  </div>

  <!-- 登录表单 -->
  <div class="login-form-container">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      class="login-form"
      label-position="top"
      hide-required-asterisk
      @submit.prevent="submitForm(ruleFormRef)"
    >
      <!-- 用户名输入框 -->
      <el-form-item label="用户名" prop="username" class="form-item">
        <el-input
          v-model="ruleForm.username"
          placeholder="请输入用户名或邮箱"
          size="large"
          class="login-input"
          @keyup.enter="submitForm(ruleFormRef)"
        >
          <template #prefix>
            <svg-icon icon-class="account" class="input-icon" />
          </template>
        </el-input>
      </el-form-item>

      <!-- 密码输入框 -->
      <el-form-item label="密码" prop="password" class="form-item">
        <el-input
          v-model="ruleForm.password"
          placeholder="请输入密码"
          size="large"
          :type="passwordType"
          class="login-input"
          @keyup.enter="submitForm(ruleFormRef)"
        >
          <template #prefix>
            <svg-icon icon-class="password" class="input-icon" />
          </template>
          <template #suffix>
            <div class="password-toggle" @click="showPwd">
              <svg-icon
                :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
                class="toggle-icon"
              />
            </div>
          </template>
        </el-input>
      </el-form-item>

      <!-- 验证码输入框 -->
      <el-form-item label="验证码" prop="captchaCode" class="form-item">
        <div class="captcha-container">
          <el-input
            v-model="ruleForm.captchaCode"
            placeholder="请输入验证码"
            size="large"
            class="captcha-input"
            @keyup.enter="submitForm(ruleFormRef)"
          >
            <template #prefix>
              <svg-icon icon-class="captcha" class="input-icon" />
            </template>
          </el-input>
          <div class="captcha-image-wrapper" @click="getCaptcha">
            <el-image :src="captchaBase64" class="captcha-image" fit="contain">
              <template #error>
                <div class="captcha-error">
                  <el-icon><picture-filled /></el-icon>
                  <span>点击刷新</span>
                </div>
              </template>
            </el-image>
            <div class="captcha-overlay">
              <span class="refresh-text">点击刷新</span>
            </div>
          </div>
        </div>
      </el-form-item>

      <!-- 记住我和忘记密码 -->
      <div class="form-options">
        <el-checkbox v-model="ruleForm.rememberMe" class="remember-checkbox">
          <span class="checkbox-text">记住我</span>
        </el-checkbox>
        <el-button link type="primary" class="forgot-password-btn" @click="showForgotPassword">
          忘记密码？
        </el-button>
      </div>

      <!-- 登录按钮 -->
      <el-form-item class="login-button-item">
        <el-button
          :loading="loading"
          type="primary"
          size="large"
          class="login-button"
          @click="submitForm(ruleFormRef)"
        >
          <span v-if="!loading" class="button-text">登录</span>
          <span v-else class="button-text">登录中...</span>
        </el-button>
      </el-form-item>

      <!-- 注册链接 -->
      <div class="register-link">
        <span class="register-text">还没有账号？</span>
        <el-button link type="primary" class="register-btn" @click="$emit('switch-mode')">
          立即注册
        </el-button>
      </div>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import type { FormInstance } from 'element-plus';
import { ElNotification } from 'element-plus';
import { PictureFilled } from '@element-plus/icons-vue';
import SvgIcon from '@/components/common/SvgIcon/index.vue';
import { useRouter, useRoute } from 'vue-router';
import { useUserStore } from '@/store/modules/user';
import { useCommonStore } from '@/store/modules/common';
import { usePermissionStore } from '@/store/modules/permission';
import { getCaptchaApi } from '@/api/auth';
import { WEBSITE_NAME } from '@/constants';
import { LOGIN_DEVICE_ENUM } from '@/constants/common/login-device';
import { encryptData } from '@/lib/encrypt';

const route = useRoute();
const router = useRouter();
const UserStore = useUserStore();
const CommonStore = useCommonStore();
const PermissionStore = usePermissionStore();

const ruleFormRef = ref<FormInstance>();
const captchaBase64 = ref<string>('');
const passwordType = ref<string>('password');
const loading = ref<boolean>(false);

defineProps({
  isDialog: {
    type: Boolean,
    default: false
  },
  isForgotPassword: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['switch-mode', 'forgot-password', 'back-to-login']);

// 表单验证规则
const rules = reactive({
  username: [
    {
      required: true,
      message: '请输入用户名',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 50,
      message: '用户名长度在 2 到 50 个字符',
      trigger: 'blur'
    }
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur'
    },
    {
      min: 6,
      max: 20,
      message: '密码长度在 6 到 20 个字符',
      trigger: 'blur'
    }
  ],
  captchaCode: [
    {
      required: true,
      message: '请输入验证码',
      trigger: 'blur'
    },
    {
      len: 4,
      message: '验证码长度为4位',
      trigger: 'blur'
    }
  ]
});

// 表单数据
const ruleForm = reactive({
  username: '',
  password: '',
  captchaCode: '',
  captchaKey: '',
  rememberMe: false,
  loginDevice: LOGIN_DEVICE_ENUM.PC.value.toString(), // 修复类型错误：转换为字符串
  emailCode: ''
});

onMounted(() => {
  getCaptcha();
});

/**
 * 获取验证码
 */
const getCaptcha = async () => {
  try {
    const { data } = await getCaptchaApi();
    ruleForm.captchaKey = data.captchaKey;
    captchaBase64.value = data.captchaBase64Image;
  } catch (error) {
    console.error('获取验证码失败:', error);
  }
};

/**
 * 切换密码显示/隐藏
 */
const showPwd = () => {
  passwordType.value = passwordType.value === 'password' ? 'text' : 'password';
};

/**
 * 提交表单
 */
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;

  try {
    const valid = await formEl.validate();
    if (!valid) return;

    loading.value = true;

    try {
      const encryptPasswordForm = {
        ...ruleForm,
        password: encryptData(ruleForm.password)
      };

      await UserStore.login(encryptPasswordForm);
      await CommonStore.getDictionary();
      await PermissionStore.generateRoutes(UserStore.roles);

      // 移除这里的手动重定向逻辑，现在由tokenExpiredManager统一处理
      ElNotification({
        title: '登录成功',
        message: `欢迎回来，${UserStore.userInfo.username}！`,
        type: 'success',
        duration: 3000
      });
    } catch (error) {
      // 登录失败时刷新验证码
      getCaptcha();
      throw error;
    }
  } catch (error) {
    console.error('登录失败:', error);
  } finally {
    loading.value = false;
  }
};

/**
 * 显示忘记密码
 */
const showForgotPassword = () => {
  emit('forgot-password');
};
</script>

<style lang="scss" scoped>
@use '../index.scss';

// 标题样式
.dialog-title {
  text-align: center;
  margin-bottom: 16px; // 从24px减少到16px

  .dialog-title-text {
    font-size: 24px; // 从26px减少到24px
    font-weight: 600;
    color: #303133;
    margin: 0;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
  }
}

.login-title {
  text-align: center;
  margin-bottom: 20px; // 从32px减少到20px

  .title-content {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 4px; // 从6px减少到4px

    .logo {
      width: 40px; // 从44px减少到40px
      height: 40px; // 从44px减少到40px
      margin-right: 12px; // 从14px减少到12px
      border-radius: 8px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }

    .title-text {
      font-size: 26px; // 从28px减少到26px
      font-weight: 700;
      color: #303133;
      margin: 0;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
    }
  }
}

// 表单容器
.login-form-container {
  .login-form {
    .form-item {
      margin-bottom: 12px; // 从16px减少到12px

      .input-label {
        margin-bottom: 4px; // 从6px减少到4px

        .label-text {
          font-size: 12px; // 从13px减少到12px
          font-weight: 500;
          color: #606266;
        }
      }

      // 输入框样式
      :deep(.login-input) {
        .el-input__wrapper {
          height: 40px; // 从44px减少到40px
          border-radius: 8px; // 从10px减少到8px
          border: 2px solid #e4e7ed;
          background-color: #ffffff !important; // 强制设置白色背景
          transition: all 0.3s ease;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);

          &:hover {
            border-color: #c0c4cc;
            background-color: #ffffff !important; // 悬停时保持白色背景
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
          }

          &.is-focus {
            border-color: #409eff;
            background-color: #ffffff !important; // 聚焦时保持白色背景
            box-shadow: 0 4px 16px rgba(64, 158, 255, 0.2);
          }
        }

        .el-input__inner {
          height: 36px; // 从40px减少到36px
          font-size: 14px; // 从15px减少到14px
          color: #303133;
          background-color: transparent !important; // 输入框内容区域透明背景

          &::placeholder {
            color: #c0c4cc;
            font-size: 12px; // 从13px减少到12px
          }
        }

        .input-icon {
          font-size: 15px; // 从16px减少到15px
          color: #909399;
          margin-right: 8px;
        }
      }
    }

    // 验证码容器
    .captcha-container {
      display: flex;
      gap: 8px; // 从10px减少到8px

      .captcha-input {
        flex: 1;

        :deep(.el-input__wrapper) {
          background-color: #ffffff !important; // 验证码输入框白色背景
        }
      }

      .captcha-image-wrapper {
        position: relative;
        width: 100px; // 从110px减少到100px
        height: 40px; // 从44px减少到40px
        border-radius: 8px; // 从10px减少到8px
        overflow: hidden;
        cursor: pointer;
        border: 2px solid #e4e7ed;
        transition: all 0.3s ease;

        &:hover {
          border-color: #409eff;
          box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);

          .captcha-overlay {
            opacity: 1;
          }
        }

        .captcha-image {
          width: 100%;
          height: 100%;
          display: block;
        }

        .captcha-overlay {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background: rgba(0, 0, 0, 0.6);
          display: flex;
          align-items: center;
          justify-content: center;
          opacity: 0;
          transition: opacity 0.3s ease;

          .refresh-text {
            color: white;
            font-size: 10px; // 从11px减少到10px
            font-weight: 500;
          }
        }

        .captcha-error {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          height: 100%;
          background: #f5f7fa;
          color: #909399;
          font-size: 10px; // 从11px减少到10px

          .el-icon {
            font-size: 16px; // 从18px减少到16px
            margin-bottom: 4px;
          }
        }
      }
    }

    // 表单选项
    .form-options {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 14px; // 从20px减少到14px

      .remember-checkbox {
        :deep(.el-checkbox__label) {
          .checkbox-text {
            font-size: 12px; // 从13px减少到12px
            color: #606266;
            font-weight: 400;
          }
        }

        :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
          background-color: #409eff;
          border-color: #409eff;
        }
      }

      .forgot-password-btn {
        font-size: 12px; // 从13px减少到12px
        font-weight: 500;
        padding: 0;

        &:hover {
          color: #337ecc;
        }
      }
    }

    // 登录按钮
    .login-button-item {
      margin-bottom: 12px; // 从16px减少到12px

      .login-button {
        width: 100%;
        height: 44px; // 从48px减少到44px
        font-size: 14px; // 从15px减少到14px
        font-weight: 600;
        border-radius: 8px; // 从10px减少到8px
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border: none;
        box-shadow: 0 4px 16px rgba(102, 126, 234, 0.3);
        transition: all 0.3s ease;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 8px 24px rgba(102, 126, 234, 0.4);
        }

        &:active {
          transform: translateY(0);
        }

        .button-text {
          letter-spacing: 1px;
        }

        &.is-loading {
          background: linear-gradient(135deg, #a8b3f0 0%, #b19bc8 100%);
        }
      }
    }

    // 注册链接
    .register-link {
      text-align: center;

      .register-text {
        font-size: 12px; // 从13px减少到12px
        color: #909399;
        margin-right: 8px;
      }

      .register-btn {
        font-size: 12px; // 从13px减少到12px
        font-weight: 600;
        padding: 0;

        &:hover {
          color: #337ecc;
        }
      }
    }
  }
}

// 密码切换按钮
.password-toggle {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 28px; // 从30px减少到28px
  height: 28px; // 从30px减少到28px
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    background-color: #f5f7fa;
  }

  .toggle-icon {
    font-size: 14px; // 从15px减少到14px
    color: #909399;
    transition: color 0.3s ease;
  }

  &:hover .toggle-icon {
    color: #409eff;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .login-title {
    .title-content {
      .logo {
        width: 32px; // 从36px减少到32px
        height: 32px; // 从36px减少到32px
        margin-right: 8px; // 从10px减少到8px
      }

      .title-text {
        font-size: 22px; // 从24px减少到22px
      }
    }

    .title-subtitle {
      font-size: 12px; // 从13px减少到12px
    }
  }

  .login-form-container {
    .login-form {
      .captcha-container {
        .captcha-image-wrapper {
          width: 80px; // 从90px减少到80px

          .captcha-overlay .refresh-text {
            font-size: 8px; // 从9px减少到8px
          }
        }
      }

      .login-button-item .login-button {
        height: 40px; // 从44px减少到40px
        font-size: 13px; // 从14px减少到13px
      }
    }
  }
}

// 动画效果
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.login-form-container {
  animation: fadeInUp 0.6s ease-out;
}

.form-item {
  animation: fadeInUp 0.6s ease-out;
  animation-fill-mode: both;

  @for $i from 1 through 6 {
    &:nth-child(#{$i}) {
      animation-delay: #{$i * 0.1}s;
    }
  }
}
</style>
